<?php

namespace app\api\controller;
use think\Db;
class Login extends \app\api\controller\Base {
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function userLogin(){
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[3456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json_encode(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json_encode(['status'=>3,'msg'=>'该手机号未注册，请先进行注册']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json_encode(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        if($username['user_status'] == 2){
                            return json(['status'=>100,'msg'=>'账号冻结']);
                        }else{
                            //更新token
                            $token = md5(date('YmdHis') . rand(100000,999999));
                            Db::table('up_u_user')->where('user_phone',$phone)
                                ->update(['user_token'=>$token]);
//                        $rytoken = $this->rongyun($username['user_id'],$username['user_username'],$username['user_image']);
                            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
//                        $username['rytoken'] = $rytoken['token'];
                            return json_encode(['status'=>200,'msg'=>$username]);
                        }
                    }
                }
            }
        }else{
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是登录和更换手机号(第一步) 2是注册和更换手机号(第二步) 3是忘记密码和修改密码，第三方登录和快捷登录传4)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){//echo 1;die;
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $num = rand(100000,999999);
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($type != 4){
            if(empty($username) && $type==1){
                return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
            }
            if(empty($username) && $type==3){
                return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
            }
            if(!empty($username) && $type==2){
                return json_encode(['status'=>22,'msg'=>'已经有此手机号码用户']);
            }
        }
        $sendres = $this->duanxin($phone,$num);
        if($sendres['code'] != '0'){
            return json_encode(['status'=>3,'msg'=>'短信平台错误：'.$sendres['errorMsg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json_encode(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json_encode(['status' => 200, 'msg' => md5($num)]);
        }
    }
    /**
     * 手机号码登录
     * @return bool
     * 参数：phone，code
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4成功
     */

    public  function phoneLogin(){
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];

        if(!preg_match("/^1[34578]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $username = Db::table('up_u_user')
            ->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        if($username['user_status'] == 2){
            return json(['status'=>100,'msg'=>'账号冻结']);
        }else{
            //更新token
            $token = md5(date('YmdHis') . rand(100000,999999));
            Db::table('up_u_user')->where('user_phone',$phone)
                ->update(['user_token'=>$token]);
//                        $rytoken = $this->rongyun($username['user_id'],$username['user_username'],$username['user_image']);
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
//                        $username['rytoken'] = $rytoken['token'];
            return json_encode(['status'=>200,'msg'=>$username]);
        }
//        return json_encode(['status'=>200,'msg'=>$username]);
    }

    /**
     * 注册
     * @return bool
     * 参数：phone,code,password
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4有其他未填项，5插入登录表失败，200成功
     */

    public  function userReg(){
        header("Access-Control-Allow-Origin:*");
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $pass = $_POST['password'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($pass=='' || $code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_app_count'] = $this->getAcount();
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user_username'] = $phone;
        $data['user_attestation'] = 1;//未认证
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
//            //注册完成积分+10
//            Db::table('up_integral')
//                ->insert(['integral_status'=>1,'integral_user_id'=>$id,'integral_time'=>date('Y-m-d H:i:s'),'integral_num'=>10]);
//            Db::table('up_u_user')
//                ->where('user_id',$id)
//                ->setInc('user_integral',10);
//            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
//            $user['rytoken'] = $rytoken['token'];
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }
    }

    /**
     * 忘记密码或修改密码
     * @return bool
     * 参数：phone,code，type
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPassOne(){
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $type = $_POST['type'];//（1是忘记密码，2是修改密码）忘记密码更新token，修改密码不更新token
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
        //TODO 修改密码成功后如果直接登录那么就要更新token
        $token = md5(date('YmdHis').rand(100000,999999));
        //,'user_token'=>$token
        if($type == 1){
            $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_token'=>$token]);
            if($res){
//                if($type == 1){
//                    $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
//                    $user['rytoken'] = $rytoken['token'];
//                }
                return json_encode(['status'=>200,'msg'=>'ok']);
            }else{
                return json_encode(['status'=>3,'msg'=>'系统错误']);
            }
        }else{
            return json_encode(['status'=>200,'msg'=>'ok']);
        }
    }

    /**
     * phone，newpass
     * 修改或者忘记密码第二步
     * @return string
     */
    public  function forgetPassTwo(){
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $new = $_POST['newpass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($new == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }

        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_password'=>md5($new)]);
        if($res){
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码重置失败']);
        }
    }
    /**
     * 原密码新密码1——输入原密码
     * oldpass  不加密
     * @return string
     */
    public  function oldPass(){
        header("Access-Control-Allow-Origin:*");
        $uid = $_POST['user_id'];
        $pass = $_POST['oldpass'];

        $my = Db::table('up_u_user')->where('user_id',$uid)->value('user_password');
        if(md5($pass) == $my){
            return json_encode(['status'=>200,'msg'=>'原来密码输入正确']);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码错误']);
        }
    }
    /**
     * 原密码新密码2——输入新密码
     * newpass   不加密
     * @return string
     */
    public  function newPass(){
        header("Access-Control-Allow-Origin:*");
        $uid = $_POST['user_id'];
        $pass = $_POST['newpass'];
        $res = Db::table('up_u_user')->where('user_id',$uid)->update(['user_password'=>md5($pass)]);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>3,'msg'=>'重置错误']);
        }
    }
    /**
     * 更换手机号——1：给旧手机发送验证码
     * 参数： phone，code
     * @return string
     */
    public function changephone_old_yzm()
    {
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    /**
     * 更换手机号——2：提交新手机
     * 参数：phone，code
     * @return string
     */
    public function changephone_new_yzm()
    {
        $phone = trim($_POST['phone'],' ');
        $uid = $_POST['user_id'];
        $code = trim($_POST['code'],' ');
        if($phone == "" || $code == ""){
            return json_encode(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }
        //=============================================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if(empty($res)){
            return json_encode(['status'=>0,'msg'=>'不是同一个手机号']);
        }
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res2 = Db::table('up_u_user')->where('user_id',$uid)->update(['user_phone'=>$phone]);
        if($res2){
            $new = Db::table('up_u_user')->where('user_id',$uid)->find();
            return json_encode(['status'=>200,'msg'=>$new]);
        }else{
            return json_encode(['status'=>0,'msg'=>'更新失败']);
        }

    }
    //================第三方登录====================

    /**
     * 微信或者qq登录
     * wqtoken,type(1是微信，2是qq)
     * @return string
     */
    public  function wqLogin()
    {
        header("Access-Control-Allow-Origin:*");
        $wxtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = 'user_wx_token';
        }else{
            $field = 'user_qq_token';
        }
        $username = Db::table('up_u_user')->where($field, $wxtoken)->find();
        if (!empty($username)) {
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $res = Db::table('up_u_user')->where($field, $wxtoken)->update(['user_token' => $token]);
            if ($res) {
                //===禁用和启用====
                if($username['user_status'] != 1){
                    return json_encode(['status' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
                }
                //======end======
                $user = Db::table('up_u_user')->where($field, $wxtoken)->find();
//                $rytoken = $this->rongyun($user['user_id'], $user['user_username'], $user['user_image']);
//                if($rytoken['code'] != 200){
//                    return json_encode(['status'=>0,'msg'=>$rytoken['errorMessage']]);
//                }
//                $user['rytoken'] = $rytoken['token'];
                return json_encode(['status' => 200, 'msg' => $user]);
            } else {
                return json_encode(['status' => 3, 'msg' => '数据库出错']);
            }
        }else{
            return json_encode(['status' => 4, 'msg' => '查无此人']);
        }

    }
    /**
     * 微信或者qq第一次登录第一步
     * wqtoken，phone，code，name，image，type
     * @return string
     */
    public  function wqFirstLogin()
    {
        header("Access-Control-Allow-Origin:*");
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }else{
            $field = '_qq_';
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $name = $_POST['name'];
        $image = $_POST['image'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 6501){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            //第一次用微信绑定好了，第二次又用另一个微信绑定时判断（qq同理）
            if($username["user{$field}token"]){
                return json_encode(['status'=>3,'msg'=>'已绑定同类型第三方了']);
            }
            //=========end==============
            $token = md5(date('YmdHis').rand(100000,999999));
            $data = array();
            $data['user_token'] = $token;
            $data['user'.$field.'token'] = $wqtoken;
            $data['user'.$field.'nickname'] = $name;
            $data['user'.$field.'image'] = $image;
            $user = Db::table('up_u_user')->where('user_phone',$phone)->field('user_username,user_image')->find();
            if(!$user['user_username']){
                $data['user_username'] = $name;
            }
            if(!$user['user_image']){
                $data['user_image'] = $image;
            }
            $res = Db::table('up_u_user')->where('user_phone',$phone)->update($data);
            $res2 = Db::table('up_u_user')->where('user_phone',$phone)->find();
            if($res){
                return json_encode(['status'=>2000,'msg'=>$res2]);
            }else{
                return json_encode(['status'=>3,'msg'=>'绑定失败']);
            }
        }else{
            return json_encode(['status'=>200,'msg'=>'ok']);//200直接进入下一步
        }





    }
    /**
     * 微信或者qq第一次登录第二步
     * wqtoken，phone，name，image，type
     * @return string
     */
    public  function wqFirstLoginTwo()
    {
        header("Access-Control-Allow-Origin:*");
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }else{
            $field = '_qq_';
        }
        $phone = $_POST['phone'];
        $name = $_POST['name'];
        $image = $_POST['image'];
        $pass = $_POST['pass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'绑定步骤出错，您是怎么走到这一步的']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $data['user_image'] = $image;//用户名字和头像同步一下
        $data['user_username'] = $name;//
        $data['user_app_count'] = $this->getAcount();
        $data['user_password'] = md5($pass);
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                //->field('user_id,user_username,user_image')
                ->find();
//            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
//            if($rytoken['code'] != 200){
//                return json_encode(['status'=>0,'msg'=>$rytoken['errorMessage']]);
//            }
//            $user['rytoken'] = $rytoken['token'];
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }

    }
    /**
     * 绑定微信或者qq
     * user_id,wqtoken,name,image,type(1微信 2qq)
     */
    public  function weixinqq()
    {
        header("Access-Control-Allow-Origin:*");
        $user_id = $_POST['user_id'];
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }else{
            $field = '_qq_';
        }
        $have = Db::table('up_u_user')->where("user{$field}token", $wqtoken)->find();
        //第一次用微信绑定好了，第二次又用另一个微信绑定时判断（qq同理）
        if($have){
            return json_encode(['status'=>0,'msg'=>'已被绑定']);
        }
        //=========end==============
        $name = $_POST['name'];
        $image = $_POST['image'];
        $data = array();
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_username,user_image')->find();
        if(!$user['user_username']){
            $data['user_username'] = $name;
        }
        if(!$user['user_image']){
            $data['user_image'] = $image;
        }
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($data);
        if($res){
            $user = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }

    }
    /**
     * 解绑微信或者qq
     * user_id,type(1微信 2qq)
     */
    public  function weixinqqdel()
    {
        header("Access-Control-Allow-Origin:*");
        $user_id = $_POST['user_id'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }else{
            $field = '_qq_';
        }

        $data = array();
        $data['user'.$field.'token'] = '';
        $data['user'.$field.'nickname'] = '';
        $data['user'.$field.'image'] = '';
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($data);
        if($res){
            $user = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'解绑失败']);
        }

    }
}